package tournamentData;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Observable;
import java.util.Set;

public class TargetAssignment extends Observable {

	private final HashMap < Integer, Target > assignments;

	public TargetAssignment() {
		this.assignments = new HashMap < Integer, Target >();
	}

	public void assignTarget(int playerID, Target target) {
		if (this.hasPlayerAssigned(target)) {
			this.removeAssignmentForTarget(target);
		}
		this.assignments.put(playerID, target);
		this.setChanged();
		this.notifyObservers();
	}

	public boolean hasPlayerAssigned(Target target) {
		return this.assignments.containsValue(target);
	}

	public boolean hasTargetAssigned(int playerID) {
		return this.assignments.containsKey(playerID);
	}

	public Target getTargetForPlayer(int playerID) {
		return this.assignments.get(playerID);
	}

	public void removeAssignmentForPlayer(int playerID) {
		this.assignments.remove(playerID);
		this.setChanged();
		this.notifyObservers();
	}

	public void removeAssignmentForTarget(Target target) {
		Iterator < Entry < Integer, Target >> iterator = this.assignments.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry < Integer, Target > entry = iterator.next();
			if (entry.getValue().equals(target)) {
				iterator.remove();
			}
		}
		this.setChanged();
		this.notifyObservers();
	}

	public Set < Entry < Integer, Target >> getAllTargetAssignments() {
		return this.assignments.entrySet();
	}

	public boolean hasPlacesAssigned(int targetNumber) {
		Iterator < Entry < Integer, Target >> iterator = this.assignments.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry < Integer, Target > entry = iterator.next();
			if (entry.getValue().getNumber() == targetNumber) {
				return true;
			}
		}
		return false;
	}

	public int getPlayerForTarget(Target target) {
		Iterator < Entry < Integer, Target >> iterator = this.assignments.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry < Integer, Target > entry = iterator.next();
			if (entry.getValue().equals(target)) {
				return entry.getKey();
			}
		}
		return -1;
	}

	public void resetAllAssignments() {
		Integer [] participants = TournamentData.getInstance().getAllParticipants();
		for (int i = 0; i < participants.length; i++) {
			this.assignments.remove(participants [i]);
		}
		this.setChanged();
		this.notifyObservers();
	}
}
